#include "headfiles.h"

using namespace std;

// Return 0, if neither word1 or word2
//        1, is word1
//        2, is word2
static int checkWord(string &word, const char *word1, const char *word2) {
    int ret;
    ret = strcmp(word.c_str(), word1);
    if (ret == 0) {
        return 1;
    }

    ret = strcmp(word.c_str(), word2);
    if (ret == 0) {
        return 2;
    }

    return 0;
}

// If either word is not contained, return -1
int calcShortestDist(const char *file_name, 
                     const char *word1, 
                     const char *word2,
                     int &min_dist_word1_loc,
                     int &min_dist_word2_loc) {
    ifstream fs;
    fs.open(file_name, fstream::in);
    if (!fs.is_open()) {
        cout << "File " << file_name << " open error!" << endl;
        return -1;
    }

    string word;
    int word1_loc = -1;
    int word2_loc = -1;
    int min_dist = 0xFFFFFFF;

    int index = 0;
    while (fs >> word) {
        if (word.empty()) {
            break;
        }

        int word_res = checkWord(word, word1, word2);
        // word1 or word2 have not met
        if (word_res == 1) {
            word1_loc = index;
            if (word2_loc != -1) {
                if (word1_loc - word2_loc < min_dist) {
                    min_dist = word1_loc - word2_loc;
                    min_dist_word1_loc = word1_loc;
                    min_dist_word2_loc = word2_loc;
                }
            }
        }

        if (word_res == 2) {
            word2_loc = index;
            if (word1_loc != -1) {
                if (word2_loc - word1_loc < min_dist) {
                    min_dist = word2_loc - word1_loc;
                    min_dist_word1_loc = word1_loc;
                    min_dist_word2_loc = word2_loc;
                }
            }
        }

        index++;
    }
    fs.close();

    return min_dist;   
}

